package org.googlecode.openapi_java;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class ContainerFactory<E extends IVkPossession> {
	
	
	private final Factory<E> factory;
	public ContainerFactory(Factory<E> factory){
		this.factory = factory;
	}
	public List<ProfiledContainer<E>> create(JSONArray jsonArray) throws JSONException{
		List<ProfiledContainer<E>> result = new LinkedList<ProfiledContainer<E>>();
		JSONArray jData = jsonArray.getJSONArray(0);
		Object maybeNull = jData.get(0);
		if (maybeNull.equals(JSONObject.NULL)) {
			return result;
		}
		JSONArray jProfiles = jsonArray.getJSONArray(1);

		int length = jProfiles.length();
		Map<Long, Profile> map = new HashMap<Long, Profile>();
		for (int i = 0; i < length; i++) {
			JSONObject jProfile = jProfiles.getJSONObject(i);
			Profile profile = Profile.fromJSON(jProfile);
			map.put(profile.getUid(), profile);
		}
		
		length = jData.length();
		for (int i = 1; i < length; i++) {
			E data = factory.create(jData.getJSONObject(i)); 
			ProfiledContainer<E>  p = new ProfiledContainer<E>(data, map.get(data.getOwner()));
			result.add(p);
		}
		return result;

	} 
}
